﻿CREATE PROCEDURE dbo.smenu_Tracker_Car_Remove
	@TrackerRequestID int
AS

BEGIN TRAN

INSERT INTO t_Technician_Tracker(TechnicianID, TrackerID,TrackerRequestID)
SELECT tr.TechnicianID, tc.TrackerID,@TrackerRequestID
FROM t_Tracker_Car tc
INNER JOIN t_TrackerRequest tr ON tc.VIN = tr.VIN
WHERE tr.ID = @TrackerRequestID
/**/IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

/**/DECLARE @CI int EXEC @CI = sp__Context_WorkFlow_System 1
UPDATE t_Tracker SET StatusID = dbo.Tracker_Status__ToBeReturned()
FROM t_Tracker t
INNER JOIN t_Tracker_Car tc    ON t.ID   = tc.TrackerID
INNER JOIN t_TrackerRequest tr ON tr.VIN = tc.VIN
WHERE tr.ID = @TrackerRequestID
/**/IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END
		ELSE EXEC sp__Context @CI

DELETE FROM t_Tracker_Car FROM t_Tracker_Car
INNER JOIN t_TrackerRequest tr ON tr.VIN = t_Tracker_Car.VIN
WHERE tr.ID = @TrackerRequestID
/**/IF @@ERROR = 0 COMMIT TRAN
		ELSE ROLLBACK TRAN



